/**
 * 前端路由配置 - 智融财务管理系统的页面路由和导航守卫
 *
 * 开发人员：唐梓鑫
 * 开发时间：2025-10-25 至 2025-10-28
 * 模块职责：配置系统的所有页面路由，包括路由守卫、权限验证、页面标题管理等
 *
 * 技术要点：
 * - Vue Router 3.6.5路由配置和管理
 * - 路由守卫实现JWT认证验证
 * - 动态页面标题设置和面包屑导航
 * - 路由懒加载和代码分割优化
 * - 权限路由和公共路由分离管理
 *
 * 开发故事：负责前端路由架构的设计和实现，与后端认证系统深度集成，确保用户访问控制和页面导航的用户体验。
 */
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import Payments from '../views/Payments.vue'
import Products from '../views/Products.vue'
import Financing from '../views/Financing.vue'
import Reports from '../views/Reports.vue'
import Enterprises from '../views/Enterprises.vue'
import Users from '../views/Users.vue'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: '/',
  routes: [
    { path: '/login', component: Login, meta: { public: true, title: '登录' } },
    { path: '/', redirect: '/dashboard', meta: { public: true } },
    { path: '/dashboard', component: Dashboard, meta: { requiresAuth: true, title: '数据看板' } },
    { path: '/payments', component: Payments, meta: { requiresAuth: true, title: '支付管理' } },
    { path: '/products', component: Products, meta: { requiresAuth: true, title: '产品管理' } },
    { path: '/financing', component: Financing, meta: { requiresAuth: true, title: '融资服务' } },
    { path: '/reports', component: Reports, meta: { requiresAuth: true, title: '报表AI' } },
    { path: '/enterprises', component: Enterprises, meta: { requiresAuth: true, title: '企业管理' } },
    { path: '/users', component: Users, meta: { requiresAuth: true, title: '用户管理' } }
  ]
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta && to.meta.title) document.title = `智融财务管理系统 · ${to.meta.title}`
  if (to.matched.some(r => r.meta && r.meta.requiresAuth)) {
    if (!token) return next({ path: '/login', query: { redirect: to.fullPath } })
  }
  // 已登录访问登录页则跳转到看板
  if (to.path === '/login' && token) return next('/dashboard')
  next()
})

export default router
